import BaseMapper from '../../db/mapper/BaseMapper'
import db from '../../db'
import TABLES from '../../db/util/table'
import { formatTimestamp, generateUUID } from '../../util'
import R from '../../vo/R'

class ContactService {
  sessionListMapper = new BaseMapper(
    db,
    TABLES.SESSION_LIST.TABLE_NAME,
    TABLES.SESSION_LIST.TABLE_ID_COLUMN
  )

  chatListMapper = new BaseMapper(
    db,
    TABLES.SESSION_INFO.TABLE_NAME,
    TABLES.SESSION_INFO.TABLE_ID_COLUMN
  )

  userContactMapper = new BaseMapper(db , TABLES.USER_CONTACT.TABLE_NAME , TABLES.USER_CONTACT.TABLE_ID_COLUMN);



  /**
   * 新增联系人
   * @param data
   */
  async saveContact(data) {
    console.log('联系人:' , data)
    const {applyId , targetId ,remark , contactInfo , contactType , friendPermission , source , status } = data
    const contactList = await this.userContactMapper.list({contactId : targetId})

    console.log('查询结果', contactList)
    // 如果为空直接新增
    if (contactList.list.length === 0) {
      const insertObj = {
        userId: applyId,
        contactId: targetId,
        avatar: contactInfo.avatar,
        nickname: contactInfo.nickname,
        email: contactInfo.email,
        phone: contactInfo.phone,
        area: contactInfo.area,
        areaCode: contactInfo.areaCode,
        contactRemark: remark,
        type: contactType,
        friendPermission,
        createTime: Date.now(),
        createUser: applyId,
        source,
        status
      }
      const insertResult = await this.userContactMapper.save(insertObj)
      return R.ok("添加成功")
    } else {
      const contact = contactList.list[0]
      if (contact.status === 1) {
        return R.fail("对方已经是好友，无需重复添加")
      } else if (contact.status === 5) {
        return R.fail("已被对方拉黑")
      }

      contact.status = 6
      const res = await this.userContactMapper.updateById(contact)
      if (res.changes > 0) {
        return R.ok("更新成功")
      }
    }


  }

}

export default ContactService
